﻿using UnityEngine;



public class GravityComponent : MonoBehaviour
{
    [Header("Gravity Settings")]
    [SerializeField] private float gravity = -9.81f; // 标准重力值
    [SerializeField] private float groundCheckDistance = 0.4f;
    [SerializeField] private LayerMask groundLayer;
    [SerializeField] private float verticalVelocity = -9.8f; // 当前垂直速度

    private CharacterController _controller;
    private bool _isGrounded;

    void Awake()
    {
        _controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        HandleGravity();
    }

    private void HandleGravity()
    {
        // 地面检测（使用球形检测更可靠）
        _isGrounded = Physics.CheckSphere(
            transform.position + _controller.center,
            groundCheckDistance,
            groundLayer
        );

        if (_isGrounded)
        {
            // 贴地时重置垂直速度（保留微小负速度防止浮空）
            if (verticalVelocity < 0)
            {
                verticalVelocity = -2f;
            }
        }
        else
        {
            // 应用重力加速度
            verticalVelocity += gravity * Time.deltaTime;
        }

        // 应用垂直速度
        _controller.Move(Time.deltaTime * verticalVelocity * Vector3.up);
    }

    // 可视化地面检测范围
    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Vector3 checkPosition = transform.position + transform.GetComponent<CharacterController>().center;
        Gizmos.DrawWireSphere(checkPosition, groundCheckDistance);
    }


}